package com.hrt.common.web;

import com.btcode.common.AbstractSingleton;
import com.btcode.db.result.PageResult;
import com.btcode.json.IJsonConver;
import com.btcode.orm.model.ModelPageResult;
import com.btcode.web.core.respone.ResultFlag;
import com.btcode.web.core.unit.URLUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

public class JsonRespone extends com.btcode.web.core.respone.JsonRespone {

    public JsonRespone() {
        super();
    }

    protected IJsonConver getJsonConver() {
        return AbstractSingleton.getInstance(JsonConver.class);
    }

    @Override
    public void outputObj(Object obj, ResultFlag resultFlag, String resultFlagDesc)
        throws IOException {
        if (obj == null) {
            obj = "";
        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("platform", URLUtil.getProjectName());
        result.put("result_flag", resultFlag.toString());
        result.put("result_flag_dsc", resultFlagDesc);

        if (obj instanceof PageResult) {
            PageResult pageResult = (PageResult) obj;
            result.put("page_info", pageResult.getPageInfo());
            obj = pageResult.getData();
        }
        else if(obj instanceof ModelPageResult){
            ModelPageResult pageResult = (ModelPageResult) obj;
            result.put("page_info", pageResult.getPageInfo());
            obj = pageResult.getData();
        }

        if (!(obj instanceof Collection<?>)) {

            List<Object> objList = new ArrayList<>();
            objList.add(obj);
            obj = objList;

        }

        result.put("data", obj);

        String jsonResult = getJsonConver().toJson(result);

        outputString(jsonResult);
    }
}
